package com.mohe.shanpao.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoClientHandler extends ChannelInboundHandlerAdapter {

	private final ByteBuf firstMessage;

	public EchoClientHandler(int firstMessageSize) {
		if (firstMessageSize <= 0) {
            throw new IllegalArgumentException("firstMessageSize: " + firstMessageSize);
        }
        firstMessage = Unpooled.buffer(firstMessageSize);
        for (int i = 0; i < firstMessage.capacity(); i ++) {
            firstMessage.writeByte((byte) i);
        }
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//		ByteBuf m = (ByteBuf) msg;
//
//		try {
//			while (m.isReadable()) {
//				System.out.print((char) m.readByte());
//				System.out.flush();
//			}
//
//		} finally {
//			m.release();
//		}
		
//		System.out.println("client = "+msg.toString());
		
//		ByteBuf out = ctx.alloc().buffer();
//		out.discardReadBytes();
//		out.writeBytes(m);
//		ctx.write(out);
//		ctx.flush();
		
//		System.out.println("client:"+m.toString());
		
		Message m = (Message)msg;
		System.out.println("client: "+ m.getTimestamp() + " ===== "+m.getValue());
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

//	@Override
//	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		System.out.println("first:"+firstMessage.toString());
//		ctx.write(firstMessage);
//		ctx.flush();
//	}
}
